// 
//  Copyright © 2009 Jiří Zárevúcky <zarevucky.jiri@gmail.com>
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as
//  published by the Free Software Foundation, either version 3 of the
//  License, or (at your option) any later version.
// 
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Affero General Public License for more details.
// 
//  You should have received a copy of the GNU Affero General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// 


using System;
using System.Threading;

namespace Galaxium.Protocol.Xmpp.Library.Utility
{
	public static class Timeout
	{
		// TODO: check if there's something better in some library
		
		public static void Start (int timeout, Action action)
		{
			if (timeout == -1) {
				action ();
				return;
			}

			Exception exc = null;
			Thread thr = new Thread (delegate () {
				try { action (); }
				catch (ThreadAbortException) {}
				catch (Exception e) { exc = e; }
			});
			thr.IsBackground = true;
			thr.Start ();
			thr.Join (timeout);
			if (thr.IsAlive) {
				thr.Abort ();
				exc = new TimeoutException ();
			}
			if (exc != null)
				throw exc;
		}
	}
}
